package com.lq.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.lq.domain.User;
import com.lq.service.UserService;
import com.opensymphony.xwork2.ActionSupport;


/***
 * 
 * @author Administrator
 *
 */
@Controller
@Scope("prototype")
public class UserAction extends ActionSupport {
	@Autowired
	private UserService userService;
	private User user;
	private List<User> userList;
	private String appVersion;
	private String json;
	
	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public String getAppVersion() {
		return appVersion;
	}

	public void setAppVersion(String appVersion) {
		this.appVersion = appVersion;
	}

	public String execute() throws Exception {
		return null;
	}

	public String login() {
		if (!user.getUsername().isEmpty() && !user.getPassword().isEmpty()) {
			User user2 = userService.login(user);
			if (user2 != null) {
				return SUCCESS;
			}
		}
		this.addFieldError("user.username", "用户名或密码错误!");
		return INPUT;
	}
	
	public void loginApp(){
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			String json = userService.Login(user, appVersion);
			System.out.println(json);
			out = response.getWriter();
			out.print(json);//json放这里
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(out != null){
				out.close();
			}
		}
	}
	
	public String addUI() {
		return "addUser";
	}

	public String updateUI() {
		user = userService.findUserById(user.getId());
		return "updateUser";
	}

	public String add() {
		userService.addUser(user);
		return SUCCESS;
	}

	public String delete() {
		userService.deleteUser(user.getId());
		return SUCCESS;
	}

	public String update() {
		userService.updateUser(user);
		return SUCCESS;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String queryAllUser() {
		userList = userService.findAllUser();
		return "userList";
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

}
